package cn.demo.weixin.ma.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.demo.common.utils.CollectionUtils;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * wechat mp configuration
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMaProp.class)
@Slf4j
public class WxMaConfig {

    private final WxMaProp prop;
    private static Map<String, WxMaService> maServices;

    public static WxMaService getMaService(String appId) {
        WxMaService wxService = maServices.get(appId);
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appId=[%s]的配置，请核实！", appId));
        }
        return wxService;
    }

    @PostConstruct
    public void init() {
        List<WxMaProp.Config> configs = this.prop.getConfigs();
        if (CollectionUtils.isEmpty(configs)) {
            log.info("请配置微信小程序的appid和secret，如不需要请删除代码");
            return ;
        }

        maServices = configs.stream()
                .map(config -> {
                    WxMaDefaultConfigImpl maConfig = new WxMaDefaultConfigImpl();
                    maConfig.setAppid(config.getAppId());
                    maConfig.setSecret(config.getSecret());
                    maConfig.setToken(config.getToken());
                    maConfig.setAesKey(config.getAesKey());
                    maConfig.setMsgDataFormat(config.getMsgDataFormat());
                    WxMaService service = new WxMaServiceImpl();
                    service.setWxMaConfig(maConfig);
                    return service;
                }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));
    }


}
